package cre.tool.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

/**
 * @Author penglai
 * @Date 2017/3/2.
 */
public class AESUtils {

    public static final String PWD_KEY = "penglaiishack!!!";

    private static byte[] getBytes(String string) throws UnsupportedEncodingException {
        return string.getBytes("utf-8");
    }

    // 加密
    public static String encrypt(String str) throws Exception {
        byte[] raw = getBytes(PWD_KEY);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
        IvParameterSpec iv = new IvParameterSpec(getBytes("0102030405060708"));//使用CBC模式，需要一个向量iv，可增加加密算法的强度

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(str.getBytes("utf-8"));

        return Base64.encodeBase64String(encrypted);
    }

    // 解密
    public static String decrypt(String password) throws Exception {
        byte[] raw = getBytes(password);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        IvParameterSpec iv = new IvParameterSpec(getBytes("0102030405060708"));
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] encrypted1 = Base64.decodeBase64(password);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original, "utf-8");
        return originalString;
    }


    public static void main(String[] args) throws Exception {
        String content = "jdbc:mysql://10.1.10.202:3306/dt_core";

        String p = encrypt(content);
        System.out.println(p);

        System.out.println(decrypt(p));
    }

}
